package com.ychs.controller;

import com.ychs.bean.Menu;
import com.ychs.bean.Role;
import com.ychs.bean.RoleMenu;
import com.ychs.bean.User;
import com.ychs.service.IMenuService;
import com.ychs.service.IRoleMenuService;
import com.ychs.service.IRoleService;
import com.ychs.service.IUserService;
import com.ychs.utils.VerifyCodeUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description: 描述【用户登录】
 * Copyright: Copyright (c) 2018
 * Company: 英才汇硕信息技术有限公司
 *
 * @author tianchuanjie
 * @version 1.0
 * @created 2019/1/26 10:34
 */
@Controller
public class LoginController {

    private Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleMenuService roleMenuService;

    @Autowired
    private IMenuService menuService;


    /**
     * 访问登录页面
     *
     * @param request 请求
     * @param session session
     * @return 登录页面
     */
    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpSession session) {
        //查询所有角色
        List<Role> roleList = roleService.query();
        session.setAttribute("roleList",roleList);
        //请求转发到页面
        request.setAttribute("roleList", roleList);
        return "/admin/login";
    }

    /**
     * 生成验证码
     *
     * @param request
     * @param response
     * @param session
     * @throws ServletException
     * @throws IOException
     */
    @GetMapping("VerifyCode")
    public void VerifyCode(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws ServletException, IOException {
        // 生成一个验证码
        logger.debug("-----" + session.getId());
        Map<String, Object> codeInfo = VerifyCodeUtils.getCode();
        String code = (String) codeInfo.get("code");
        BufferedImage bufferedImage = (BufferedImage) codeInfo.get("image");
        // 将验证码的字符串信息保存在session里
        session.setAttribute("code", code);
        System.out.println(code);
        // 设置响应头，禁止图片缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        // 设置响应类型为图片
        response.setContentType("image/jpeg");
        // 获取响应字节流
        ServletOutputStream sos = response.getOutputStream();
        // 将图片输出到响应字节流中
        ImageIO.write(bufferedImage, "jpeg", sos);
    }

    /**
     * @param role     roleId  角色id
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @return
     */
    @PostMapping("/login")
    public String menuInfo(int role, String username, String password, String code, HttpSession session, HttpServletRequest request) {
        //根据username password 判断用户是否存在
        //存在然后根据roleId 查询菜单列表
        User user = userService.queryInfo(username, password);
        //用户信息可以在整个项目中使用
        session.setAttribute("userInfo", user);
        //验证码不区分大小写
        session.setAttribute("roleId", role);
        if (code.equalsIgnoreCase(session.getAttribute("code").toString())) {
            //如果用户存在 判断角色是否正确
            if (user != null) {
                //如果role一致 则用户可以登录 加载不同菜单
                if (user.getUserRoleId() == role) {
                    //根据roleId 查询角色对应的菜单信息 菜单id
                    List<RoleMenu> roleMenuList = roleMenuService.queryByRoleId(role);
                    //遍历list 得到menuId 然后根据menuId查询menuPid  将信息转发到页面
                    HashMap<Integer, Object> hashMap = new HashMap<>();
                    for (RoleMenu roleMenu : roleMenuList) {
                        int menuId = roleMenu.getMenuId();
                        //根据菜单id 得到对象调用菜单pid
                        Menu menu = menuService.queryByMenuId(menuId);
                        hashMap.put(menuId, menu);
                    }
                    request.setAttribute("menuListHashMap", hashMap);
                } else {
                    logger.debug("该用户没有该分配角色");
                    session.setAttribute("tip", "该用户没有该分配角色");
                    return "redirect:login";
                }
            } else {
                logger.debug("该用户不存在");
                session.setAttribute("tip", "该用户不存在");
                return "redirect:login";
            }

        } else {
            logger.debug("验证码错误");
            session.setAttribute("tip", "验证码错误");
            return "redirect:login";
        }
        return "/admin/menu";
    }
}
